﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Admin.CYT369.Com.WebBase
{
    class UpperCaseNamingPolicy : System.Text.Json.JsonNamingPolicy
    {
        public override string ConvertName(string name)
        {
            return name;
        }
    }

    [SystemExceptionProcessor]
    public class BaseController : Microsoft.AspNetCore.Mvc.Controller
    {
        public static object s_lock_object = new object();
        private UserSession m_UserSession = null;
        public UserSession UserSession {
            get {
                if (m_UserSession == null)
                {
                    lock (s_lock_object)
                    {
                        if (m_UserSession == null)
                        {
                            m_UserSession = this.HttpContext.RequestServices.GetService(typeof(UserSession)) as UserSession;
                        }
                    }
                }

                return m_UserSession;
            }
        }

        public int GetUserId()
        {
            var item = this.User.Claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier).FirstOrDefault();
            int id = 0;
            if (item != null)
            {
                int.TryParse(item.Value, out id);
            }

            return id;
        }

        public ContentResult Content(bool b)
        {
            return base.Content(b.ToString().ToLower());
        }

        public JsonResult DefaultJson(object obj)
        {
            var setting = new System.Text.Json.JsonSerializerOptions()
            {
                PropertyNamingPolicy = new UpperCaseNamingPolicy()
            };


            return base.Json(obj, setting);
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
        }
    }

    public class AllowAnonymousController : BaseController
    {
    }

    [Authorize]
    public class AuthorizeController : BaseController
    {

    }
}
